from django.db import models
from django.utils.http import urlquote
from django.utils.encoding import smart_unicode


class Source(models.Model):
	name = models.CharField(max_length=255, unique=True)
	description = models.TextField(null=True,blank=True)
 
	def __unicode__(self):
		return smart_unicode(self.name)

	class Meta:
		db_table = 'sti_source'
		ordering = ('name',)


class Knows(models.Model):
	topic = models.ForeignKey(
		'Topic',  related_name="expert_set")
	source = models.ForeignKey(Source,)
	person = models.ForeignKey(
		'Person',  related_name="expertise_set")

	class Meta:
		db_table = 'sti_knows'
		unique_together = (('topic', 'person', 'source'),)
		verbose_name = 'knowledge'


class Topic(models.Model):
	name = models.CharField(max_length=70, blank=False, unique=True, )

	def aux_field(self, field_name):
		lst = self.topicaux_set.filter(field_name=field_name)
		if len(lst):
			return lst[0].field_value
		return None

	def get_absolute_url(self):
		return urlquote("/topics/%s/" % self.name.lower())

	def __unicode__(self):
		return smart_unicode(self.name)

	class Meta:
		ordering = ('name',)
		db_table = 'sti_topic'


class TopicAux(models.Model):
	TOPIC_AUX_FIELDS = tuple(enumerate(('MathWorld', 'PlanetMath', 'Wikipedia', 'ISI')))
		
	topic = models.ForeignKey(Topic,)
	url_type = models.IntegerField(
		choices=TOPIC_AUX_FIELDS,  verbose_name='Field URL type')
	url = models.TextField( verbose_name='URL',blank=True,null=True)

	def get_icon(self):
		return '/images/%s.ico' % self.get_url_type_display().lower()

	class Meta:
		db_table = 'sti_topic_aux'
		ordering = ('url_type', 'url')


class TopicAssoc(models.Model):
	ASSOCIATION_TYPES = tuple(enumerate(("parent to child", "related")))

	from_topic = models.ForeignKey(Topic, related_name="outbound", )
	to_topic = models.ForeignKey(Topic, related_name="inbound", )
	source = models.ForeignKey(Source, )
	assoc_type = models.IntegerField(
		choices=ASSOCIATION_TYPES,  verbose_name='association type')

	class Meta:
		db_table = 'sti_topic_assoc'
		ordering = ('from_topic', 'to_topic', 'source', 'assoc_type',)
		# unique_together = (('from_topic', 'to_topic', 'source', 'assoc_type',),)
		verbose_name = 'topic association'


class PersonManager(models.Manager):
	def nameWithTopics(self):
		from django.db import connection
		cursor = connection.cursor()
		pSql = ("SELECT id, last_name, first_name FROM sti_person "
				"ORDER BY last_name, first_name")
		cursor.execute(pSql)
		people = cursor.fetchall()
		cursor.close()

		pTopics = []
		for pid, ln, fn in people:
			cursor2 = connection.cursor()
			sql2 = (
				"SELECT p.name "
				"FROM sti_topic p, sti_knows k "
				"WHERE k.person_id = %s AND k.topic_id = p.id "
				"ORDER BY p.name")
			cursor2.execute(sql2, (pid,))
			topics2d = cursor2.fetchall()
			topics1d = [t for t, in topics2d]
			pTopics.append([ln, fn, topics1d])
		return pTopics
		

class Person(models.Model):
	objects = PersonManager()
	source = models.ForeignKey(Source,)
	last_name = models.CharField(max_length=127)
	first_name = models.CharField(max_length=127)

	def __unicode__(self):
		return smart_unicode("%s, %s [%s]" % (self.last_name, self.first_name, self.source))

	class Meta:
		db_table = 'sti_person'
		ordering = ('last_name', 'first_name',)
		# problematic if the same person is discovered in multiple sources,
		# or if two different people have the same first and last names
		unique_together = (('last_name', 'first_name',),)


class PersonAux(models.Model):
	person = models.ForeignKey(Person)
	field_name = models.CharField(max_length=255, )
	field_value = models.TextField()

	class Meta:
		db_table = 'sti_person_aux'
		unique_together = (("person", "field_name"),)
		ordering = ("person",)







class Entry(models.Model):
	name = models.CharField(max_length=127,unique = True, blank = False, )
	
	def __unicode__(self):
		return smart_unicode(self.name)
	
	class Meta:
		db_table = 'sti_extra_entry'
		ordering = ('name',)
		verbose_name_plural = 'entries'
		
class EntryAux(models.Model):
	entry = models.ForeignKey(Entry,)
	source = models.TextField(verbose_name='Source',)
	
	def __unicode__(self):
		return smart_unicode("%s <%s>" % (self.entry,self.source))
		
	class Meta:
		db_table = 'sti_extra_entry_aux'
		ordering = ('entry',)


class Author(models.Model):
	last_name = models.CharField(max_length=127,verbose_name='Last name')
	first_name = models.CharField(max_length=127,verbose_name='First name',blank=True,null=True)
	
	def __unicode__(self):
		if self.first_name: return smart_unicode(' '.join([self.first_name,self.last_name]))
		else: return smart_unicode(self.last_name)
	
	class Meta:
		db_table = 'sti_extra_author'
		verbose_name = 'Author'
		ordering = ('last_name','first_name',)
		unique_together = (('last_name','first_name'),)

class Publisher(models.Model):
	name = models.CharField(max_length=127,unique=True)
	address = models.CharField(max_length=127,blank=True,null=True)
	city = models.CharField(max_length=63,blank=True,null=True)
	state_province = models.CharField(max_length=63,blank=True,null=True)
	country = models.CharField(max_length=63,blank=True,null=True)
	website = models.TextField(blank=True,null=True)
	
	def __unicode__(self):
		return smart_unicode(self.name)
	
	class Meta:
		db_table = 'sti_extra_publisher'
		verbose_name = 'Publisher'
		ordering = ('name',)


class Book(models.Model):
	title = models.CharField( max_length=127,verbose_name = 'Title')
	edition = models.IntegerField(verbose_name = 'Edition',blank=True,null=True)
	authors = models.ManyToManyField(Author,blank=True,null=True)
	publisher = models.ForeignKey(Publisher,blank=True,null=True)
	topics = models.ManyToManyField(Entry,through='TOC',blank=True,null=True)
	ISBN = models.CharField(max_length=31,verbose_name='ISBN',unique=True,blank=True,null=True)
	year = models.CharField(max_length=31,verbose_name='Year',blank=True,null=True)
	icon_url = models.TextField(verbose_name = 'Icon URL',blank=True,null=True)
	url = models.TextField( verbose_name='URL',blank=True,null=True)
	
	def __unicode__(self):
		if self.edition:
			return smart_unicode("%s, %dEd" % (self.title,self.edition))
		else:
			return smart_unicode(self.title)
	
	def get_absolute_url(self):
		if self.edition:	return urlquote("/books/%s&%dEd/" % (self.title,self.edition))
		return urlquote("/books/%s" % self.title)

	class Meta:
		db_table = 'sti_extra_book'
		verbose_name = 'Book'
		unique_together = (('title','edition'),)
		ordering = ('title','edition')


class TOC(models.Model):
	book = models.ForeignKey(Book)
	topic = models.ForeignKey(Entry)
	position = models.CharField(max_length=63) # format: c.c.c
	page = models.CharField(max_length=63,blank=True,null=True)

	def __unicode__(self):
		return smart_unicode("%s: Position %s, Page %s, <%s>" % (self.topic,self.position,self.page,self.book))

	class Meta:
		db_table = 'sti_extra_toc'
		verbose_name = 'Table of Content'
		unique_together = (('book','topic','position'),)
		ordering = ('book','position','topic')

class Course(models.Model):
	name = models.CharField( max_length=127)
	semester = models.CharField( max_length=127)
	description = models.TextField()
	books = models.ManyToManyField(Book,through='Uses',blank=True,null=True)

	def get_absolute_url(self):
		return urlquote("/courses/%s&%s/" % (self.semester,self.name))

	def __unicode__(self):
		return smart_unicode("[%s] %s -- %s" % (self.semester, self.name,self.description))

	class Meta:
		db_table = 'sti_extra_course'
		ordering = ('semester','name',)
		unique_together = (('name','semester'),)

class Lecture(models.Model):
	course = models.ForeignKey(Course)
	number = models.CharField( max_length=127,verbose_name = 'Lecture #')
	source = models.TextField(verbose_name='Source')
	topics = models.ManyToManyField(Entry,blank=True,null=True,through='Covers')

	def __unicode__(self):
		return smart_unicode("Lecture %s, %s" % (self.number,self.course))
	
	class Meta:
		db_table = 'sti_extra_lecture'
		ordering = ('course','number',)
		unique_together = (('course','number'),)
		verbose_name = 'lecture'

class Covers(models.Model):
	lecture = models.ForeignKey(Lecture)
	topic = models.ForeignKey(Entry)
	position = models.IntegerField()
	
	def __unicode__(self):
		return smart_unicode("<%s> %s : %d" % (self.lecture,self.topic,self.position))
	
	class Meta:
		db_table = "sti_extra_covers"
		verbose_name = 'Topics covered in lectures'
		verbose_name_plural = 'Topics covered in lectures'
		unique_together = (('lecture','topic','position'))
		ordering = ('lecture','position')
		
class Alias(models.Model):
	entry = models.ForeignKey(Entry)
	alias = models.ForeignKey(Topic,null=True,blank=True)
	
	def __unicode__(self):
		if self.alias:
			return smart_unicode("%s : %s" % (self.entry, self.alias))
		else:
			return smart_unicode("%s : none" % self.entry)
	
	class Meta:
		db_table = 'sti_extra_alias'
		verbose_name = 'Alias'
		verbose_name_plural = 'aliases'
		unique_together = (('entry','alias'))
		


class Uses(models.Model):
	book = models.ForeignKey(Book)
	course = models.ForeignKey(Course)
	
	def __unicode__(self):
		return smart_unicode("%s : %s" % (self.course, self.book))
	
	class Meta:
		db_table = 'sti_extra_uses'
		ordering = ('course','book')

	
	
	
	
import ims.sti.admin

__all__ = ['Source', 'Knows', 'Topic', 'TopicAux', 'TopicAssoc', 'Person', 'PersonAux','Course','Lecture','Alias','Entry','Book','TOC','Uses','EntryAux','Covers','Author','Publisher']
